#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 05 14:59:47 2021

@author: Kai Lu @ SYSU
"""
# 导入 需要的 library 库
import numpy as np  # 科学计算
import matplotlib.pyplot as plt  # 画图
import matplotlib as mpl
import scipy.signal as sg  # 导入 scipy 的 signal 库 命名为 sg

mpl.rc('lines', linewidth=4)  # , linestyle='-.'
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams['xtick.labelsize'] = 10
plt.rcParams['ytick.labelsize'] = 10
plt.rcParams['savefig.dpi'] = 300  # 图片像素
plt.rcParams['figure.dpi'] = 300  # 分辨率

def sinc(_x):
    return np.piecewise(_x, [_x != 0, _x == 0], [lambda _x: np.sin(_x) / _x, 1])


# np.piecewise(x, [x >= 0, x < 0], [lambda x: np.log(1 + x), lambda x: - np.log(1 - x)])

t = np.linspace(-20, 20, num=101, endpoint=True)
# x_t = triangle(t)
x_t = sinc(t)

# sg is scipy.signal
t1 = np.linspace(-1, 3, num=41, endpoint=True)

f1t = np.array([2 if 0 < t < 1 else 0 for t in t1])
t2 = np.linspace(-1, 3, num=41, endpoint=True)  # t in [-1,3]
f2t = np.array([t if 0 < t < 2 else 0 for t in t2])
yt = sg.convolve(f1t, f2t, 'full') * 0.1  # calculate convolution
t3 = np.linspace((min(t1)+min(t2)), (max(t1)+max(t2)), num=(len(t1)+len(t2)-1), endpoint=True)
# t3 = np.array([t * 0.1 for t in range(-20, 61)])  # t in [-1+-1, 3+3]
# 开始绘图
plt.plot(t3, yt, label='conv')
plt.grid(True)
plt.show()

# # y = b * np.exp(a * t) * np.sin(omega * t)
# fig = plt.figure(dpi=300)
# plt.xlabel('Time (s)')
# plt.ylabel('Mag')
# # plt.title(r'$Ce^{\alpha t}, C \in \mathbb{C} , \alpha \in \mathbb{C}$: ' + fr'C={C}, $\alpha={alpha}$')
# plt.plot(t, x_t, label=r'Sinc Signal')
# # plt.plot(t, x_t_im, label=r'Imag')
# plt.legend(loc='upper left')
# plt.grid(color='k', linestyle='-', linewidth=0.1)
# # plt.grid(axis='x', linewidth=1, linestyle='--', color='0.75')
# # plt.grid(axis='y', linewidth=1, linestyle='--', color='0.75')
# plt.savefig('Signal_Sinc.png', bbox_inches='tight', pad_inches=0.02, dpi=300)
